package io2.nio.pipeline2;

public class Pipeline {
    private HandlerContext head;
    private HandlerContext tail;

    public Pipeline() {
        head = new HandlerContext(new Handler() {
            @Override
            public void read(HandlerContext context, String obj) {
                context.read(obj + "head... ");
            }

            @Override
            public void write(HandlerContext context, String obj) {
                System.out.println("Write -> " + obj);
            }
        });
        tail = new HandlerContext(new Handler() {
            @Override
            public void read(HandlerContext context, String obj) {
                System.out.println("Read -> " + obj);
            }

            @Override
            public void write(HandlerContext context, String obj) {
                context.write(obj + "tail... ");
            }
        });
        head.setNext(tail);
        tail.setPrev(head);
    }

    public void addLast(Handler handler) {
        HandlerContext context = new HandlerContext(handler);
        tail.getPrev().setNext(context);
        context.setPrev(tail.getPrev());

        context.setNext(tail);
        tail.setPrev(context);
    }

    public void fireRead(String obj) {
        head.read(head, obj);
    }

    public void fireWrite(String obj) {
        tail.write(tail, obj);
    }
}
